/**
 *  File: BaseBaoFuService.java
 *  Date         Author      Changes
 *  2016-10-2    wangtq       Create
 *
 */
package com.kunpu.mami.channel.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.kunpu.mami.channel.common.ResConstants;
import com.kunpu.mami.channel.domain.RequestParams;
import com.kunpu.mami.channel.domain.TransContent;
import com.kunpu.mami.channel.domain.TransReqBF0040001;
import com.kunpu.mami.channel.domain.TransRespBF0040001;
import com.kunpu.mami.channel.exception.MamiiException;
import com.kunpu.mami.channel.utils.BaofooClient;
import com.kunpu.mami.channel.utils.http.SimpleHttpResponse;
import com.kunpu.mami.channel.utils.rsa.RsaCodingUtil;

/**
 * 发送宝付提现
 * @author wangtq
 * @date 2016-10-2
 * @version 0.1
 *
 */
public class BaseSendRepayService extends BaseSendService{
	private final Logger       logger = LoggerFactory.getLogger(this.getClass());
	//private static final String txn_sub_type = "5";
	@Value("${repay_keyPath}")
	private String repay_keyPath;//代付商户私钥
	@Value("${repay_cerPath}")
	private String repay_cerPath;//代付宝付公钥


	/**
	 * @throws Exception
	 */
	public void  rePayService (TransReqBF0040001 transReqData1) {
		// TODO Auto-generated method stub
		logger.info("============================= 提现请求宝付 start ======================= \n 入参：{}",transReqData1.toString());
		String dataType = "xml"; // 数据类型 xml/json
		TransContent<TransReqBF0040001> transContent = new TransContent<TransReqBF0040001>(
				dataType);
		List<TransReqBF0040001> trans_reqDatas = new ArrayList<TransReqBF0040001>();
		trans_reqDatas.add(transReqData1);
		transContent.setTrans_reqDatas(trans_reqDatas);

		String bean2XmlString = transContent.obj2Str(transContent);
		logger.info("----------提现请求宝付加密前报文: {}",bean2XmlString); 

		String keyStorePath = repay_keyPath;
		String keyStorePassword = keyPwd ;
		String pub_key = repay_cerPath;
		String origData = bean2XmlString;

		/**
		 * 加密规则：项目编码UTF-8
		 * 第一步：BASE64 加密
		 * 第二步：商户私钥加密
		 */
		origData =  new String(new Base64().encodeBase64(origData.getBytes()));//Base64.encode(origData);
		String encryptData = RsaCodingUtil.encryptByPriPfxFile(origData,
				keyStorePath, keyStorePassword);
		logger.info("----------提现请求宝付私钥加密-结果 {}",encryptData); 
		RequestParams params = new RequestParams();
		params.setMemberId(Integer.parseInt(member_id));
		params.setTerminalId(Integer.parseInt(terminal_id));
		params.setDataType(dataType);
		params.setDataContent(encryptData);// 加密后数据
		params.setVersion("4.0.0");
		params.setRequestUrl(requestUrl);
		SimpleHttpResponse response = null;
		try {
			logger.info("----------提现请求宝付报文：发送参数为：{}",params.toString()); 
			response = BaofooClient.doRequest(params);
		} catch (Exception e) {
			logger.error("---------提现请求宝付异常,错误信息为：",e.getMessage(),e); 
			throw new MamiiException(ResConstants.PAY_ANALYSIS_EXISTENT.getCode() ,"代付接口解析错误。"+response.getEntityString());
		}
		String reslut = response.getEntityString();
		logger.info("----------提现请求宝付返回报文为：{}",reslut); 
		System.out.println(reslut);
		TransContent<TransRespBF0040001> str2Obj = new TransContent<TransRespBF0040001>(dataType);
	
		/**
		 * 在商户终端正常的情况下宝付同步返回会以密文形式返回,如下：
		 * 此时要先宝付提供的公钥解密：RsaCodingUtil.decryptByPubCerFile(reslut, pub_key)
		 * 再次通过BASE64解密：new String(new Base64().decode(reslut))
		 * 在商户终端不正常或宝付代付系统异常的情况下宝付同步返回会以明文形式返回
		 */
		//明文返回处理可能是报文头参数不正确、或其他的异常导致；
		if (reslut.contains("trans_content")) {
			logger.info("----------提现请求处理宝付返回密文报文----"); 
			//明文返回
			//我报文错误处理
			str2Obj = (TransContent<TransRespBF0040001>) str2Obj.str2Obj(
					reslut, TransRespBF0040001.class);

			//LOGGER.error("e",str2Obj);
			throw new MamiiException(ResConstants.PAY_CASH_EXCEPTION.getCode(), "提现请求失败！");
			// 业务逻辑判断
		} else {
			logger.info("----------提现请求处理宝付返回密文报文----"); 
			//密文返回
			//第一步：公钥解密
			reslut = RsaCodingUtil.decryptByPubCerFile(reslut, pub_key);
			//第二步BASE64解密
			reslut = new String(new Base64().decode(reslut));
			//LOGGER.info("提现成功。返回结果"+reslut);
			str2Obj = (TransContent<TransRespBF0040001>) str2Obj.str2Obj(
					reslut, TransRespBF0040001.class);
			logger.info("----------提现请求处理宝付返回密文结果为：｛｝----",str2Obj); 
			if(!str2Obj.getTrans_head().getReturn_code().equals("0000")) {
				//LOGGER.error("e",str2Obj);
				throw new MamiiException(ResConstants.PAY_CASH_EXCEPTION.getCode(), "提现请求失败！");
			}
		}
		logger.info("============================= 提现请求宝付 end ==========================");
	}

	
	public String getRepay_keyPath() {
		return repay_keyPath;
	}
	public void setRepay_keyPath(String repay_keyPath) {
		this.repay_keyPath = repay_keyPath;
	}
	public String getRepay_cerPath() {
		return repay_cerPath;
	}
	public void setRepay_cerPath(String repay_cerPath) {
		this.repay_cerPath = repay_cerPath;
	}

	
	

	
}
